//有状态的登录页面
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:http/http.dart';
import 'package:myapp52/constants/api_constants.dart';
import 'package:myapp52/constants/ui_constants.dart';
import 'package:toastification/toastification.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPage();
}

class _LoginPage extends State<LoginPage> {
  var phoneCtrl = TextEditingController();
  var pwdCtrl = TextEditingController();
  String phone = ''; //电话输入框中的内容
  String pwd = ''; //密码输入框中的内容
  bool hidePwd = true;

  @override
  void initState() {
    phoneCtrl.text='13501234567';
    phone=phoneCtrl.text;
    pwdCtrl.text='123456';
    pwd=pwdCtrl.text;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Uiconstants.COLOR_PAGE_BG,
        appBar: AppBar(
          toolbarHeight: 0,
        ),
        body:SingleChildScrollView(
          child: Padding(
          padding: EdgeInsets.all(20),
          child: Column(
            // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              SizedBox(height: 120),
              //logo
              Image.asset(
                'assets/img/logo.png',
                width: 240,
                height: 240,
                fit: BoxFit.cover,
              ),
              SizedBox(height: 20),
              //账号输入框
              TextField(
                controller: phoneCtrl,

                decoration: InputDecoration(
                  contentPadding: EdgeInsets.all(0),

                  hintText: '请输入手机号码',
                  hintStyle: TextStyle(color: Colors.black45),
                  border: OutlineInputBorder(
                    borderSide: BorderSide.none,
                    borderRadius: BorderRadius.circular(10),
                  ),
                  // border: InputBorder.none,
                  filled: true,
                  fillColor: Color(0xFFF0F0F0),
                  prefixIcon: Icon(
                    Icons.phone_android_sharp,
                    color: Uiconstants.COLOR_THEME_GREEN,
                  ),
                  suffixIcon: IconButton(
                    onPressed: () => phoneCtrl.clear(),
                    icon: Icon(
                      Icons.cancel_rounded,
                      color: Uiconstants.COLOR_THEME_BLUE,
                    ),
                  ),
                ),
                onChanged: (val) => phone = val,
              ),
              SizedBox(height: 20),
              // 密码输入框
              TextField(
                controller: pwdCtrl,
                obscureText: hidePwd,
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.all(0),
                  hintText: '请输入登录密码',
                  hintStyle: TextStyle(color: Colors.black45),
                  border: OutlineInputBorder(
                    borderSide: BorderSide.none,
                    borderRadius: BorderRadius.circular(10),
                  ),
                  filled: true,
                  fillColor: Color(0xFFF0F0F0),
                  prefixIcon: Icon(
                    Icons.lock,
                    color: Uiconstants.COLOR_THEME_GREEN,
                  ),
                  suffixIcon: IconButton(
                    onPressed: () => setState(()=>hidePwd = !hidePwd),
                    icon: Icon(
                      hidePwd?Icons.visibility_off:Icons.visibility,
                      color: Uiconstants.COLOR_THEME_BLUE,
                    ),
                  ),
                ),
                onChanged: (val) => pwd = val,
              ),
              //登录按钮
              SizedBox(height: 30),
              SizedBox(
                width: double.infinity,
                height: 50,
                child: ElevatedButton(
                  onPressed: () async {
                    var url = APIconstants.userLogin;
                    var res = await post(
                      Uri.parse(url),
                      headers: {"Content-Type": "application/json"},
                      body: jsonEncode({'phone': phone, 'pwd': pwd}),
                    );
                    var body = jsonDecode(res.body);
                    if(body['code']==2000){
                      toastification.show(
                        context: context,
                        title: Text('欢迎回来${phone}'),
                        type: ToastificationType.success,
                        alignment: Alignment.bottomCenter,
                        autoCloseDuration: Duration(seconds: 3),
                        closeButton: ToastCloseButton(
                          showType:CloseButtonShowType.none 
                        ),
                        showIcon: false,
                        backgroundColor: Colors.black,
                        foregroundColor: Uiconstants.COLOR_PAGE_BG,
                        style: ToastificationStyle.simple
                      );
                      var storage = FlutterSecureStorage();
                      storage.write(key: 'userToken', value: body['token']);
                      Navigator.pushReplacementNamed(context, '/home');
                    }else{
                      showDialog(context: context, builder: (context)=>AlertDialog(
                      title: Text('错误'),
                      content: Text(body['msg']),
                      actions: [TextButton(onPressed: ()=>Navigator.pop(context), child: Text('确定'))],
                      ));
                    }
                    //  检验用户名是否合法
                    // 密码舒服是否合法
                    // 提交服务器接口验证
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Uiconstants.COLOR_THEME_GREEN,
                  ),
                  child: Text(
                    '登      录',
                    style: TextStyle(color: Colors.white, fontSize: 16),
                  ),
                ),
              ),
              //忘记密码
              TextButton(
                onPressed: () => {print('跳到忘记密码')},
                child: Text(
                  '忘记密码',
                  style: TextStyle(color: Uiconstants.COLOR_THEME_BLUE),
                ),
              ),
            ],
          ),
          
        ),
        ) 
      );
  }
}
